// =============================================================
// CShell
// ---------------------------------------
// Author : Woo-Hyun Kim
// Email : woorung@icu.ac.kr or woorung@nhncorp.com
// Date : Jul. 25, 2006
// =============================================================
#include "CShell.h"
//---------------------------------------------------------------
CShell::CShell() : CProcess()
{
	command = "";
	command_result = "";
}
//---------------------------------------------------------------
CShell::CShell(string &cmd) : CProcess()
{ 
	command = cmd;
	command_result = "";
}
//---------------------------------------------------------------
CShell::~CShell() 
{
}
//---------------------------------------------------------------
string &CShell::getCommand()
{ 
	return command;
}
//---------------------------------------------------------------
// parent process
//---------------------------------------------------------------
string &CShell::getCommandResult()
{
	return getDataFromPipe();

/*
	if(command_result=="") {
		char buf[1024];
		string tmp = "";
		memset((char *)buf, '\0', sizeof(buf));
		while(read(pipefd[0], buf, sizeof(buf)-1)>0) {
			tmp += buf;
			memset((char *)buf, '\0', sizeof(buf));
		}

		int len = tmp.length();
		if(tmp[len-1]=='\n') command_result = tmp.substr(0, tmp.length()-1);
		else command_result = tmp;

		return command_result;
	}
	else return command_result;
*/
}
//---------------------------------------------------------------
// child process
//---------------------------------------------------------------
void CShell::run()
{
	if(command=="") {
		cout << "[warning] : no command" << endl;
		return;
	}

	command_result = execute(command, command_result);

	// save results to pipe
	write(pipefd[1], command_result.c_str(), command_result.length());
}
//---------------------------------------------------------------
string &CShell::execute(string &command, string &command_result)
{
    char buf[1024];
    memset((char *)buf, '\0', sizeof(buf));

    FILE *p = popen(command.c_str(), "r");
    if(!p) {
        cout << "pipe open error : " << command << endl;
    }

    // to contain the result of the command execution
    string tmp = "";
    memset((char *)buf, '\0', 1024);
    while(fgets(buf, 1023, p)!=0) {
        tmp += buf;
        memset((char *)buf, '\0', 1024);
    }

    pclose(p);

    string result;
    int len = tmp.length();
    if(tmp[len-1]=='\n') result = tmp.substr(0,tmp.length()-1);
    else result = tmp;

    command_result = result;

    return command_result;
}
//----------------------------------------------------------------
